<template>
  <div class="feed-config">
    <header class="mb20">
      <h3 class="f18">请编辑需要反馈问题的模块</h3>
      <div class="btn-wrap">
        <el-button type="primary" @click="saveRenew">保存并更新</el-button>
      </div>
    </header>

    <div class="list-wrap" ref="sortableRef">
      <div class="list-item mb20" v-for="(item, index) in formList" :key="item.clsId">
        <el-row>
          <el-col :span="12">
            <el-form :model="item" :inline="true" ref="formRef">
              <el-form-item label="名称" prop="clsName" :rules="[{ validator, trigger: 'blur' }]">
                <el-input v-model="item.clsName" />
              </el-form-item>
            </el-form>
          </el-col>
          <el-col :span="12">
            <div class="item-btn-wrap">
              <el-icon @click="delLevel1(item, index)">
                <DeleteFilled />
              </el-icon>
              <p class="my-handle ml24"><img src="@/assets/images/mall/drag.png" alt="" /></p>
            </div>
          </el-col>
        </el-row>

        <!-- 选题列表 -->
        <div class="level2">
          <div class="topic-item" v-for="(topic, topicIndex) in item.item" :key="topic.clsId">
            <el-form :model="topic" ref="formRef">
              <el-form-item prop="itemName" :rules="[{ validator, trigger: 'blur' }]">
                <div class="input">
                  <el-input v-model="topic.itemName" placeholder="请输入" class="mb10" style="width: 320px" />
                  <el-icon @click="delLevel2(item.item, topicIndex)">
                    <DeleteFilled />
                  </el-icon>
                </div>
              </el-form-item>
            </el-form>
          </div>
          <el-button :icon="CirclePlusFilled" type="primary" link @click="addLevel2(item.item)">添加选题</el-button>
        </div>
      </div>

      <!-- 删除时的二次确认框 -->
      <ActionSubmitDialog
        v-model:isOpen="_isOpen"
        :message="'温馨提示：您正在执行删除操作，请在删除后点击保存并更新，之后系统才会进行最终删除~~'"
        @submit="returnSubmit"
      />

      <div class="add-level1">
        <el-button :icon="CirclePlusFilled" type="primary" link @click="addLevel1">添加模板</el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from "vue";
import { CirclePlusFilled } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import Sortable from "sortablejs";
import { getFeedbackClassifyList, saveFeedbackClassify, sort } from "@/api/mall/feedback";
import ActionSubmitDialog from "@/components/ActionSubmitDialog";

const sortableRef = ref();
const formList = ref([]);
const formRef = ref();
const delObj = ref({});
const _isOpen = ref(false);

//确认删除当前item
const returnSubmit = () => {
  if (delObj.value.level === 1) {
    if (formList.value.length <= 1) return ElMessage.error("至少保留一条数据");
    formList.value.splice(delObj.value.index, 1);
    _isOpen.value = false;
  } else if (delObj.value.level === 2) {
    if (delObj.value.item.length <= 1) return ElMessage.error("至少保留一条数据");
    delObj.value.item.splice(delObj.value.index, 1);
    _isOpen.value = false;
  }
};

/**
 * 初始化列表
 */
const init = async () => {
  const res = await getFeedbackClassifyList();
  formList.value = res.data;
};
const initSortable = () => {
  new Sortable(sortableRef.value, {
    animation: 150,
    ghostClass: "blue-background-class",
    handle: ".my-handle",
    onEnd: ({ newIndex, oldIndex }) => {
      if (newIndex == oldIndex) return;
      formList.value?.splice(newIndex, 0, formList.value?.splice(oldIndex, 1)[0]);
      const newArray = formList.value?.slice(0);
      formList.value = [];
      nextTick(function () {
        formList.value = newArray;
      });
    }
  });
};
/**
 * 添加一级
 */
const addLevel1 = () => {
  formList.value.push({ item: [] });
};
/**
 * 添加二级
 */
const addLevel2 = item => {
  item.push({});
};
/**
 * 删除一级
 */
const delLevel1 = (item, index) => {
  delObj.value = { item, index, level: 1 };
  console.log(111111111111111, item, index);
  if (formList.value.length <= 1) return ElMessage.error("至少保留一条数据");
  if (item.clsId) {
    _isOpen.value = true;
  } else {
    formList.value.splice(index, 1);
  }
};
/**
 * 删除二级
 */
const delLevel2 = (item, index) => {
  delObj.value = { item, index, level: 2 };
  console.log(222222222, item, index);
  if (item.length <= 1) return ElMessage.error("至少保留一条数据");
  if (item[index].clsId) {
    _isOpen.value = true;
  } else {
    item.splice(index, 1);
  }
};
const isValidate = ref(false); //表单是否校验通过
const saveRenew = async () => {
  await validateFun();
  if (isValidate.value) {
    //校验通过，请求保存接口，并更新
    await saveFeedbackClassify(formList.value);
    await sort(formList.value.map(v => v.clsId));
    ElMessage.success("保存成功");
    init();
  }
};
const validateFun = async () => {
  const refs = formRef.value;
  const isb = [];
  for (let item of refs) {
    await item.validate(valid => {
      isb.push(valid);
    });
  }
  isValidate.value = isb.every(v => v);
};
/**
 * 校验
 */
const validator = (rule, value, callback) => {
  const regex = /^[^!@#$%^&*]*$/;
  if (!value || !value.trim()) {
    callback(new Error("选题不能为空"));
  } else if (value.length > 20) {
    callback(new Error("长度不能超过20"));
  } else if (!regex.test(value)) {
    callback(new Error("禁止输入特殊字符"));
  } else {
    callback();
  }
};
onMounted(() => {
  nextTick(() => {
    initSortable();
  });
  init();
});
</script>

<style lang="scss" scoped>
p,
h3 {
  margin: 0;
}

:deep(.el-form-item.el-form-item--default) {
  margin-bottom: 0;
}

.feed-config {
  header {
    display: flex;
    justify-content: space-between;

    h3 {
      line-height: 32px;
    }
  }

  .list-wrap {
    max-height: calc(100vh - 280px);
    overflow-y: scroll;

    .list-item {
      border-radius: 0px 0px 0px 0px;
      border: 1px solid #dcdfe6;

      & > .el-row {
        background-color: #f5f7fa;
        padding: 10px 16px 18px;
        border-bottom: 1px solid #dcdfe6;
      }

      .item-btn-wrap {
        display: flex;
        justify-content: flex-end;
        align-items: center;
        height: 100%;

        ::v-deep(.el-icon) {
          color: rgb(144, 147, 153);
        }

        img {
          width: 16px;
          height: 16px;
          vertical-align: bottom;
          cursor: pointer;
        }
      }

      .level2 {
        padding: 16px;

        .topic-item {
          display: flex;
          align-items: center;
          margin-bottom: 20px;

          .input {
            display: flex;
            align-items: center;
            gap: 10px;

            ::v-deep(.el-icon) {
              color: rgb(144, 147, 153);
            }
          }

          ::v-deep(.mb10) {
            margin: 0 !important;
          }
        }
      }
    }

    .add-level1 {
      padding: 14px 16px;
      background-color: #f5f7fa;

      .el-button {
        width: 100%;
        justify-content: flex-start;
      }
    }
  }
}
</style>
